package top.javadev.typora.minio;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.minio.errors.MinioException;
import top.javadev.typora.minio.config.UploadConfig;
import top.javadev.typora.minio.util.Utils;

/**
 * @author javadev.top
 * @date 2021/10/11
 */
public class App {

    public static void main(String[] args) {
        if (args.length > 0) {

            App app = new App();
            UploadConfig config = Utils.loadConfig();
            for (String path : args) {
                String url = app.upload(path, config);
                // Typora 会提取脚本的输出作为地址，将markdown上图片链接替换掉
                System.out.println(config.getHost() + "/" + config.getBucketName() + "/" + url);
            }
        } else {

        }
    }

    /**
     * 上传
     *
     * @param path
     *            文件路径
     * @param config
     *            配置信息
     * @return {@link String}
     */
    public String upload(String path, UploadConfig config) {
        StringBuilder url = new StringBuilder();
        try {
            MinioClient minioClient = MinioClient.builder().endpoint(config.getHost())
                .credentials(config.getAccessKey(), config.getSecretKey()).build();

            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(config.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(config.getBucketName()).build());
            }
            if (config.getCustomKey() != null && config.getCustomKey().trim().length() > 0) {
                url.append(config.getCustomKey()).append("/");
            }
            url.append(System.nanoTime());
            url.append(Utils.getSuffix(path));
            minioClient.uploadObject(UploadObjectArgs.builder().bucket(config.getBucketName()).object(url.toString())
                .filename(path).build());

        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return url.toString();
    }

}
